<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <!--按需调整-->
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="所属应用" prop="appId">
          <el-select v-model="listQuery.param.appId" placeholder="所属应用" style="width: 100%;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="(value, key) in apps" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台编码" prop="serviceCode">
          <el-input v-model="listQuery.param.serviceCode" placeholder="平台编码" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="服务描述" prop="serviceDesc">
          <el-input v-model="listQuery.param.serviceDesc" placeholder="服务描述" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 150px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />

      <!--按需调整-->
      <el-table-column label="所属应用" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.appDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台编码" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.serviceCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务名称" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.serviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务描述" min-width="120px" align="left">
        <template v-slot="{row}">
          <span>{{ row.serviceDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租户号" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.tenantId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.edit" command="edit"><i class="el-icon-edit"> 编辑</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 编辑页面 -->
    <el-drawer
      :visible.sync="visible"
      direction="rtl"
      size="65%"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :show-close="false"
    >
      <template v-slot:title>
        <div class="drawer-header">
          <span>{{ title[state] }}</span>
          <div>
            <el-button icon="el-icon-close" @click="handleClose">
              取消
            </el-button>
            <el-button v-if="state !=='detail'" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
              确认
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="120px">
        <el-input v-model="formData.id" type="hidden" />
        <!--按需调整-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属应用" prop="appId">
              <el-select v-model="formData.appId" :disabled="state==='detail'" placeholder="所属应用" style="width: 100%;" class="filter-item" @change="handleAppNameChange">
                <el-option v-for="(value, key) in apps" :key="key" :label="value" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台编码" prop="serviceCode">
              <el-input v-model="formData.serviceCode" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="formData.serviceName" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务描述" prop="serviceDesc">
              <el-input v-model="formData.serviceDesc" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务地址" prop="serviceUri">
              <el-input v-model="formData.serviceUri" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务类型" prop="serviceType">
              <el-radio v-model="formData.serviceType" :disabled="state==='detail'" label="local">本地</el-radio>
              <el-radio v-model="formData.serviceType" :disabled="state==='detail'" label="remote">远程</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行方式" prop="execType">
              <el-radio v-model="formData.execType" :disabled="state==='detail'" label="sync">同步</el-radio>
              <el-radio v-model="formData.execType" :disabled="state==='detail'" label="async">异步</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据类型" prop="dataType">
              <el-radio v-model="formData.dataType" :disabled="state==='detail'" label="json">JSON</el-radio>
              <el-radio v-model="formData.dataType" :disabled="state==='detail'" label="xml">XML</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="Y">启用</el-radio>
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="N">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" :readonly="state==='detail'" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs v-model="activeName">
          <el-tab-pane label="入参" name="first">
            <atomic-param-form ref="paramForm" :param-form-data="paramFormData" />
          </el-tab-pane>
          <el-tab-pane label="出参" name="second">
            <atomic-result-form ref="resultForm" :result-form-data="resultFormData" />
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="handleClose">
          取消
        </el-button>
        <el-button v-if="state !=='detail'" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
          确认
        </el-button>
      </div>
    </el-drawer>

    <!--详情页面-->
    <!--按需替换子组件名称-->
    <!--    <component-name-detail ref="formDetail" :detail="detail" />-->

  </div>
</template>

<script>
import { handlePageList, handleSave, handleDelete } from './api.js'
import { handleApps } from '../app/api'
import permission from '@/directive/permission/index' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import AtomicParamForm from './param/index'
import AtomicResultForm from './result/index'

export default {
  // 当前页面名称（组件）
  name: 'EbApplicationServiceForm',
  // 引用组件
  components: { Pagination, AtomicParamForm, AtomicResultForm },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          // 按需调整
          id: undefined,
          appId: undefined,
          serviceCode: undefined,
          serviceDesc: undefined,
          tenantId: undefined,
          status: undefined
        }
      },
      // 状态字典
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      // 应用列表
      apps: [],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        // 按需补充
        add: ['esb:service:add'],
        edit: ['esb:service:edit'],
        del: ['esb:service:del']
      },
      // 表单校验规则
      rules: {
        // 按需调整
        appId: [{ required: true, message: '所属应用不能为空', trigger: 'change' }],
        serviceCode: [{ required: true, message: '平台的编码不能为空', trigger: 'change' }],
        serviceName: [{ required: true, message: '服务名称不能为空', trigger: 'change' }],
        serviceDesc: [{ required: true, message: '服务描述不能为空', trigger: 'change' }],
        serviceType: [{ required: true, message: '服务类型不能为空', trigger: 'change' }],
        serviceUri: [{ required: true, message: '转发地址不能为空', trigger: 'change' }],
        execType: [{ required: true, message: '执行类型不能为空', trigger: 'change' }],
        dataType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
        status: [{ required: true, message: '是否禁用状态不能为空', trigger: 'change' }]
      },
      activeName: 'first',
      // 入参data
      paramFormData: {
        state: '',
        serviceCode: ''
      },
      // 出参data
      resultFormData: {
        state: '',
        serviceCode: ''
      },
      // 详情data
      detail: {
        visible: false,
        data: {}
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()
    handleApps().then(res => {
      this.apps = res.data
    })
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      handlePageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 重置表单
    handleRestFormData() {
      // 按需调整
      this.formData = {
        id: undefined,
        appId: undefined,
        appDesc: undefined,
        serviceCode: undefined,
        serviceName: undefined,
        serviceDesc: undefined,
        serviceType: 'remote',
        serviceUri: undefined,
        execType: 'sync',
        dataType: 'json',
        callbackUrl: undefined,
        status: 'Y',
        remark: '',
        params: [],
        results: []
      }
    },
    // 选中
    handleAppNameChange(value) {
      this.formData.appDesc = this.apps[value]
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 编辑
      if (item === 'edit') {
        this.handleUpdate(row, index)
      }
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true

      this.paramFormData.serviceCode = this.formData.serviceCode
      this.paramFormData.state = this.state
      this.resultFormData.serviceCode = this.formData.serviceCode
      this.resultFormData.state = this.state

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['paramForm'].handleInit()
        this.$refs['resultForm'].handleInit()
      })
    },
    // 修改
    handleUpdate(row) {
      this.state = 'update'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)

      // 按需补充

      // 清理掉多余的属性值，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.paramFormData.serviceCode = this.formData.serviceCode
      this.paramFormData.state = this.state
      this.resultFormData.serviceCode = this.formData.serviceCode
      this.resultFormData.state = this.state

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['paramForm'].handleInit()
        this.$refs['resultForm'].handleInit()
      })
    },
    // 详情
    handleDetail(row) {
      this.state = 'detail'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)

      this.paramFormData.serviceCode = this.formData.serviceCode
      this.paramFormData.state = this.state
      this.resultFormData.serviceCode = this.formData.serviceCode
      this.resultFormData.state = this.state

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['paramForm'].handleInit()
        this.$refs['resultForm'].handleInit()
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ id: row.id }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.formData.params = this.$refs.paramForm.handleTableData()
      this.formData.results = this.$refs.resultForm.handleTableData()

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          handleSave(this.formData).then((res) => {
            //  刷新table
            this.handleFilterQuery()
            this.handleClose()
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 关闭弹出层
    handleClose() {
      this.$refs['dataForm'].resetFields()
      this.handleRestFormData()
      this.paramFormData.serviceCode = ''
      this.activeName = 'first'
      this.visible = false
    }
  }
}
</script>
<style>
.el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio.is-disabled .el-radio__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled.is-checked {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__label {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-textarea.is-disabled .el-textarea__inner {
  background-color: #ffffff !important;
}
.vue-treeselect--disabled .vue-treeselect__control {
  background-color: #ffffff !important;
}
</style>
